import React from "react";
import {Button,  Divider,Menu, Modal} from 'antd/lib';
import FinishTable from "@/components/contract/FinishTable";
import FinishHrp from "@/components/contract/FinishHrp";
import ContractFinish from "@/services/contractfinish";
import Contracts from "@/services/contracts";
import notification from "@/services/notification";
import {get} from "lodash";
import CheckDialog from "@/components/workflow/CheckDialog";
import {currentUser} from "@/services/auth";
import Workflow from "@/services/workflow";
import moment from "moment";
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import GlobalFunctions from '@/store/globalFunctions';
import {createBrowserHistory} from 'history';
const customHistory = createBrowserHistory();
const { confirm } = Modal;
export default class FinishToolbar extends React.Component {
  state = {
    loading: true,
    isnew: true,
    id: 0,//
	  userid: currentUser.id,//--操作员ID
	  bill_date: moment(),//--申请日期
	  contractsid: "",
	  code: "",//----合同编号
	  name: "",//--合同名称
	  status: 0,//--状态
    message: "",//--纪录事项
    //===================
    isedit:true,
    isdel:false,
    allow_col:[],
    colcontrol:false,
    annex:[],//--附件
    openpage:"jbxx",
    contractsdata:[],
  };
  componentWillMount() {
    let id=this.props.id;
    if(this.props.id<1 || this.props.id===undefined ){
      id=0;
    }
    let param={
      billtype: "contractfinish",
      id: id,
    }
    Contracts.getsellist(param).then(data => {
      this.setState({
        contractsdata: data,
      });
    });
     if(this.props.id<1 || this.props.id===undefined ){
       ContractFinish.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
        });
      });
     }else{
        this.setState({
          id: this.props.id,
          isnew: false,
          loading: false,
        });
       this.iseditData(this.props.id);
       this.refreshData(this.props.id) ;
     }
  }
  refreshData(id) {

    ContractFinish.get({id: id}).then(data => {
      if (data.id > 0) {
        this.setState({
          id: data.id,//
          userid: data.userid,//--操作员ID
          bill_date: moment(data.bill_date),//--申请日期
          contractsid: data.contractsid,//--合同
          code: data.code,//----编号
          name: data.name,//--名称
          status: data.status,//--状态
          message: data.message,//--纪录事项
          loading: false,
        });
      } else {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          contractsid: "",//
          code: "",//----编号
          name: "",//--名称
          status: 0,//--状态
          message: "",//--纪录事项
        });
      }
    }).catch(error => {
        this.setState({
          loading: false,
          id: id,
          userid: currentUser.id,//--操作员ID
          bill_date: moment(),//--申请日期
          contractsid: "",//--经办部门
          code: "",//----合同编号
          name: "",//--合同名称
          status: 0,//--状态
          message: "",//--纪录事项
        });
      });
}
  handleadd = () => {
       ContractFinish.getid({id: 0}).then(data => {
        this.setState({
          id: data[0].id,
          isnew: true,
          loading: false,
          isedit:true,
          isdel:false,
        });
        this.refreshData(data[0].id)
      });
  };
  ///|| str.match(/^[\s]*$/)
  isEmptyobj = (str) => {
	if(str==='' || str === null || str === 'null' || str === undefined || str === 'undefined'){
		return true;
	}else{
		return false;
	}
}
  handleSave = () => {
    let id = this.state.id;
    let userid = this.state.userid;
    let bill_date = this.state.bill_date;
    let contractsid = this.state.contractsid;
    let code =  this.state.code;
    let name =  this.state.name;
    let status =  this.state.status;
    let message =  this.state.message;
    let sourcetype =  this.state.sourcetype;
    let annexchd = this.state.annex;
    let sourceid = this.state.sourceid;
    if(this.state.openpage==="jbxx"){
       id = this.child.state.id;
       userid = this.child.state.userid;
       bill_date = this.child.state.bill_date;
       contractsid = this.child.state.contractsid;
       code =  this.child.state.code;
       name =  this.child.state.name;
       status =  this.child.state.status;
       message =  this.child.state.message;
       sourcetype =  this.child.state.sourcetype;
       annexchd = this.child.state.annex;
       sourceid = this.child.state.sourceid;
    }
    if(status ===0 && currentUser.id !==userid){
      notification.error("草稿状态，不是制单人，不能保存！");
      return;
    }
    if(status ===2){
      notification.error("已审批，不能保存！");
      return;
    }
    if(GlobalFunctions.isEmptyobj(contractsid)){
      notification.error("合同不能为空！");
      return;
    }
    if(GlobalFunctions.isEmptyobj(code)){
      notification.error("编号不能为空");
      return;
    }
    if(GlobalFunctions.isEmptyobj(name)){
      notification.error("名称不能为空");
      return;
    }
    let  annex=[]
    annexchd.forEach(file => {
      if(file.status==="done") {
         const b=[{
                  uid: file.uid,
                  name: file.name,
                  status: file.status,
                  bytstatus:file.bytstatus,
                  url: file.url
          }];
        if (annex.length < 1) {
          annex = b;
        } else {
          annex.push.apply(annex, b);
        }
      }
        });
    let data={id: id,//
            userid: userid,//--操作员ID
            bill_date: bill_date,//--申请日期
            contractsid: contractsid,
            code: code,//----合同编号
            name: name,//--合同名称
            status: status,//--状态
            message: message,
           sourcetype: sourcetype,
           annex: annex,
           sourceid: sourceid
    }
    if(this.state.isnew) {
      ContractFinish.create(data)
        .then(() => {
          this.setState({
            isnew: false,
            loading: false,
            isedit: true,
            id: data.id,//
            userid: data.userid,//--操作员ID
            bill_date: data.bill_date,//--申请日期
            contractsid: data.contractsid,
            code: data.code,//----合同编号
            name: data.name,//--合同名称
            status: data.status,//--状态
            message: data.message,
           sourcetype: data.sourcetype,
           annex: data.annex,
           sourceid: data.sourceid
          });
          notification.success("合同验收申请单新增成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
      ContractFinish.save(data)
        .then(() => {
          notification.success("合同验收申请单修改成功.");
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }
  };
  handleDelete = () => {
    if(this.child.state.status !==0){
      notification.error("不是草稿状态，不能删除！");
      return;
    }
    confirm({
      title: '确定删除合同验收申请单?',
      icon: <WarningOutlined />,
      content: this.child.state.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractFinish.delete({id: this.state.id}).then(()=>{
          notification.success("合同验收申请单删除成功.");
             ContractFinish.getid({id: 0}).then(data => {
              this.setState({
                id: data,
                isnew: true,
                loading: false,
                isedit: true,
              });
              this.refreshData(data);
            });
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  iseditData(id) {
      let item = {
        bill: "contractfinish",
        billtype:0,
        billid: id,
        userid: currentUser.id
      }
      Workflow.edit(item).then(data => {
        if(data.length>0){
              this.setState({
                isedit: data[0].edit,
                isdel: data[0].del,
                allow_col:data[0].allow_col,
                colcontrol:data[0].colcontrol,
              });
        }
      }).catch(error => {
              this.setState({
                isedit: true,
                isdel: true,
                allow_col:[],
                colcontrol:false,
              });
        });
  };
  handlebackpage= () => {
    customHistory.goBack();
  };
  handleCheck = () => {
    if(!currentUser.isAudit){
      notification.error("没有权限.");
      return;
    }
    let item={
      bill:"contractfinish",
      id:this.state.id,
      message:"",
      status: this.child.state.status,
      altermsg: "",
      warnsealuser:"",
    }
    if(this.state.status===0){
      item = {
        bill: "contractfinish",
        billtype: 0,
        billid: this.state.id,
        next_type: 1,
        message:'<div>同意</div>',
        userid: currentUser.id,
        billdate: this.state.bill_date.format('YYYY-MM-DD'),
        orgunitid: this.state.departmentid,
        status: this.state.status,
        warnsealuser:"",
        billuserid: currentUser.id,
      }
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          this.iseditData(this.state.id);
          this.refreshData(this.state.id);
          notification.success(data[0].message);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    }else{
      CheckDialog.showModal({bill_check: item})
      .onClose((result = {}) => {
          if (result.success) {
            this.iseditData(this.state.id);
            this.refreshData(this.state.id);
            // this.setState({
            //   id: item.id,
            // });
          }
        }).onDismiss(() => {
    //     navigateTo("contract/finish", true);
        });
      }
  };
  tabsClick = e => {
    this.setState({
      openpage: e.key,
    });
  };
  childchange = (data) =>{
    this.setState({
        id: data.id,//
        userid: data.userid,//--操作员ID
        bill_date: data.bill_date,//--申请日期
        contractsid: data.contractsid,
        code: data.code,//----合同编号
        name: data.name,//--合同名称
        status: data.status,//--状态
        message: data.message,
       sourcetype: data.sourcetype,
       annex: data.annex,
       sourceid: data.sourceid
    });
  };
  render() {
    if (this.state.loading) return null;
    const data={
      id: this.state.id,//
      userid: this.state.userid,//--操作员ID
      bill_date: this.state.bill_date,//--申请日期
      contractsid: this.state.contractsid,//--合同
      code: this.state.code,//----编号
      name: this.state.name,//--名称
      status: this.state.status,//--状态
      message: this.state.message,//--纪录事项
    };
    let contractcode='';
    if(this.state.contractsid>0){
      contractcode=this.state.contractsdata.filter(item => item.id===this.state.contractsid)[0].code;
    }
    return(
      <div>
        <div style={{ marginBottom: 16 }}>
        <Button type="primary" style={{margin:"10px"}} onClick={() => this.handlebackpage()}>
            <i className="fa fa-reply m-r-5" />
            返回
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleadd()}>
            <i className="fa fa-plus m-r-5" />
            新增
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleSave()} disabled ={!this.state.isedit}>
            <i className="fa fa-save m-r-5" />
            保存
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleDelete()} disabled ={this.state.isdel}>
            <i className="fa fa-trash m-r-5" />
            删除
          </Button>
          <Divider type="vertical" />
          <Button type="primary" onClick={() => this.handleCheck()}>
            <i className="fa fa-check m-r-5" />
            {this.state.status===0 ? "提交":"审核"}
          </Button>
        </div>
        <div>
          <Menu onClick={this.tabsClick} selectedKeys={this.state.openpage} mode="horizontal">
                  <Menu.Item key = "jbxx">基本信息</Menu.Item>
                  <Menu.Item key = "lchrp">联查HRP</Menu.Item>
          </Menu>
          {this.state.openpage==="jbxx" &&
          (<FinishTable data={data}  isedit={this.state.isedit}  isnew={this.state.isnew} 
          allow_col={this.state.allow_col} colcontrol={this.state.colcontrol}
          contractsdata={this.state.contractsdata}
          onRef={(ref) => { this.child = ref; }} childchange = {this.childchange}/>)}
          {this.state.openpage==="lchrp" &&
          (<FinishHrp data={data}  isedit={this.state.isedit}  isnew={this.state.isnew} 
          allow_col={this.state.allow_col} colcontrol={this.state.colcontrol}
          contractcode={contractcode}
          onRef={(ref) => { this.chdhrp = ref; }}/>)}
        </div>
      </div>
    );
  };
}

